package com.example.ssss.data;

import android.os.Message;
import android.util.Log;

import com.example.ssss.data.entity.ShareData;
import androidx.appcompat.app.AppCompatActivity;

import com.example.ssss.MainActivity;
import com.example.ssss.data.entity.ShareData;
import com.example.ssss.data.entity.TimeStamp;
import com.example.ssss.entity.Behave;
import com.example.ssss.entity.History;

import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.session.SessionDataSet;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;

public class IotdbOperation {
    public Session session;
    public void SessionStart(TimeStamp timeStamp) throws IoTDBConnectionException, StatementExecutionException {
      Thread thread =  new Thread(new Runnable() {
            @Override
            public void run() {
                String SERVER_HOST = "123.57.214.240";
                int IoTDB_PORT = 6667;

                session = new Session(SERVER_HOST, IoTDB_PORT, "root", "root");
                try {
                    session.open(false);
                } catch (IoTDBConnectionException e) {
                    e.printStackTrace();
                }

                // set session fetchSize
                session.setFetchSize(10000);

                //TODO 获取三大字符串数组
                final String wearTopic = "ESP32_wear_W0001";
                final String envTopic = "ESP32_env";
                final String behaveTopic = "RpiBehaveClient_04EA56902CB0";
                ArrayList<String> wearList = new ArrayList<>(); //wear主题：血压、心率每分钟平均值
                ArrayList<String> wearAvgList = new ArrayList<>(); //wear主题，血压、心率此次时间范围内的总的平均值
                ArrayList<String> envList = new ArrayList<>(); //env: 环境温度、环境TVOC，环境CO2每分钟平均值
                ArrayList<String> envAvgList = new ArrayList<>();//env：环境温度、环境TVOC，环境CO2此次时间范围内的总的平均值
                ArrayList<String> behaveSumList = new ArrayList<>();//behave：此次时间范围内的每种不安全行为次数统计
                String wearSql = "select AVG(*) from root."+ wearTopic +" group by (["+timeStamp.getWearBeginTimeStamp()+", "+timeStamp.getWearEndTimeStamp()+"),1m,1m);";
                String wearAvgSql = "select AVG(*) from root."+ wearTopic +" where time >="+timeStamp.getWearBeginTimeStamp()+" and time <"+timeStamp.getWearEndTimeStamp()+";";
                String envSql = "select AVG(*) from root."+ envTopic +" group by(["+timeStamp.getEnvBeginTimeStamp()+","+timeStamp.getEnvEndTimeStamp()+"),1m,1m);";
                String envAvgSql = "select AVG(*) from root."+ envTopic +" where time >="+timeStamp.getWearBeginTimeStamp()+" and time <"+timeStamp.getWearEndTimeStamp()+";";
                String behaveSumSql = "select SUM(*) from root."+ behaveTopic +" where time >="+timeStamp.getBehaveBeginTimeStamp()+" and time < "+timeStamp.getBehaveEndTimeStamp()+";";

                try {
                    SessionDataSet wearDataSet = session.executeQueryStatement(wearSql);
                    SessionDataSet wearAvgDataSet = session.executeQueryStatement(wearAvgSql);
                    SessionDataSet envDataSet = session.executeQueryStatement(envSql);
                    SessionDataSet envAvgDataSet = session.executeQueryStatement(envAvgSql);
                    SessionDataSet behaveSumDataSet = session.executeQueryStatement(behaveSumSql);
                    int k=0;
                    while (wearDataSet.hasNext()) {
                        String str = String.valueOf(wearDataSet.next());
                        wearList.add(str);
                        wearDataSet.next();
                    }

                    while (envDataSet.hasNext()) {
                        String str = String.valueOf(envDataSet.next());
                        envList.add(str);
                        envDataSet.next();
                    }


                    wearAvgList.add(String.valueOf(wearAvgDataSet.next()));
                    envAvgList.add(String.valueOf(envAvgDataSet.next()));
                    behaveSumList.add(String.valueOf(behaveSumDataSet.next()));

                } catch (StatementExecutionException | IoTDBConnectionException e) {
                    e.printStackTrace();
                }
                // 解析DataSet

                int historyid=0;
                boolean flag=true;
                int k=1;
//                for (String str: wearList) {
//                    if (flag) {
//                        Connection conn = null;
//                        Statement state = null;
//                        ResultSet rs = null;
//                        try {
//                            conn = MysqlOperation.DBUtils.getConnect();
//                            state = conn.createStatement();
//                            String sql = "select historyid from history_detail order by historyid desc";
//                            rs = state.executeQuery(sql);
//
//                            while (rs.next()) {
//                                historyid = Integer.parseInt(rs.getString(1)) + 1;
//                                break;
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        } finally {
//                            try {
//                                MysqlOperation.DBUtils.release(conn, state, rs);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                        flag = false;
//                    }
//                    String[] s = str.split("\t");
//                    if (s[4].equals("undefine") || s[1].equals("undefine") || s[2].equals("undefine") || s[3].equals("undefine")) {
//                        continue;
//                    }
//                    Double d = Double.parseDouble(s[1]);
//                    Double d1 = Double.parseDouble(s[2]);
//                    Double d2 = Double.parseDouble(s[3]);
//                    Double d3 = Double.parseDouble(s[4]);
//                    insertWear(d, d1, d2, d3, k++, historyid);
//                    ShareData shareData=(ShareData)getApplication();
//                    insertUserHistory(historyid,)
//                    Log.d("mqtt",str);
//                }
//                Log.d("mqtt","envList");
//                for (String str: envList){
//                    Log.d("mqtt",str);
//                }
//                Log.d("mqtt","behaveList");
//                for (String str: behaveList){
//                    Log.d("mqtt",str);
//                }
//                Log.d("mqtt","wearList");
//                int historyid=0;
//                boolean flag=true;
//                int k=1;
                double oxyprc=0,diaPressprc=0,heartprc=0,sysPressprc=0;
                double oxyelse=0,diaPresselse=0,heartelse=0,sysPresselse=0;
                for (String str: wearList) {
                    if (flag) {
                        Connection conn = null;
                        Statement state = null;
                        ResultSet rs = null;
                        try {
                            conn = MysqlOperation.DBUtils.getConnect();
                            state = conn.createStatement();
                            String sql = "select historyid from oxy order by historyid desc";
                            rs = state.executeQuery(sql);
                            while (rs.next()) {
                                historyid = Integer.parseInt(rs.getString(1)) + 1;
                                break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                MysqlOperation.DBUtils.release(conn, state, rs);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        flag = false;
                    }

                    String[] s = str.split("\t");
                    if (s[4].equals("null") || s[1].equals("null") || s[2].equals("null") || s[3].equals("null")) {
                        continue;
                    }
                    double d = Double.parseDouble(s[1]);
                    if(d>=95){
                        oxyprc++;
                    }
                    else{
                        oxyelse++;
                    }

                    double d1 = Double.parseDouble(s[2]);
                    if(d1>=60&&d1<=90){
                        sysPressprc++;
                    }
                    else{
                        sysPresselse++;
                    }
                    double d2 = Double.parseDouble(s[3]);
                    if(d2>=100){
                        heartprc++;
                    }
                    else{
                        heartelse++;
                    }
                    double d3 = Double.parseDouble(s[4]);
                    if(d3>=90&&d3<140){
                        diaPressprc++;
                    }
                    else{
                        diaPresselse++;
                    }
                    insertWear(d, d1, d2, d3, k++, historyid);
                    Log.d("mqtt",str);
                }
                insertUserHistory(historyid,timeStamp.getUserId());
                oxyprc/=(oxyprc+oxyelse);
                diaPressprc/=(diaPressprc+diaPresselse);
                heartprc/=(heartprc+heartelse);
                sysPressprc/=(sysPressprc+sysPresselse);
                double sum=(oxyprc+diaPressprc+heartprc+sysPressprc)/4;

//                Log.d("mqtt","envList");
//                for (String str: envList){
//                    Log.d("mqtt",str);
//                }
//                Log.d("mqtt","behaveList");
//                for (String str: behaveList){
//                    Log.d("mqtt",str);
//                }


                // 解析Avg、Sum DataSet
                int dangerousBehave = 0;


                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                String[] date1= format.format(timeStamp.getWearEndTimeStamp()).split(" ");
                String[] date2=format.format(timeStamp.getWearBeginTimeStamp()).split(" ");
                long milliseconds = timeStamp.getWearEndTimeStamp()-timeStamp.getWearBeginTimeStamp();
                long minutes = (milliseconds / 1000) / 60;
                long seconds = (milliseconds / 1000) % 60;

                History history1=new History();
                if(sum>0.95){
                    history1.setStatus("很好");
                }else if(sum>0.9){
                    history1.setStatus("好");
                }else if(sum>0.8){
                    history1.setStatus("一般");
                }else if(sum>0.7){
                    history1.setStatus("差");
                }else{
                    history1.setStatus("很差");
                }
                history1.setStartAndEndTime(date2[1].substring(0,5)+"~"+date1[1].substring(0,5));
                history1.setDate(date1[0]);

                history1.setDistance("0km");
                history1.setScore(((int)(sum*100))+"");
                history1.setDuration(minutes+"min"+seconds+"s");

                //需赋值
                int score=100,dangerousbehave = 0;
                String[] d = behaveSumList.get(0).split("\t"); 
                if (d.length >= 9) {
                    dangerousbehave = (int) Double.parseDouble(d[1]) + (int) Double.parseDouble(d[2]) + (int) Double.parseDouble(d[3])
                            + (int) Double.parseDouble(d[4]) + (int) Double.parseDouble(d[5]) + (int) Double.parseDouble(d[6])
                            + (int) Double.parseDouble(d[7])
                            + (int) Double.parseDouble(d[8]) + (int) Double.parseDouble(d[9]);

                    history1.setDangerousBehave(dangerousbehave + "");
                    //危险驾驶行为
                    Behave behave = new Behave();

                    //需赋值
                    behave.setBoth_hands_leaving_wheel(((int) Double.parseDouble(d[1])) + "");
                    behave.setEyes_closed(((int) Double.parseDouble(d[2])) + "");
                    behave.setNo_face_mask(((int) Double.parseDouble(d[3])) + "");

                    behave.setNot_buckling_up(((int) Double.parseDouble(d[4])) + "");
                    behave.setSmoke(((int) Double.parseDouble(d[5])) + "");

                    behave.setCellphone(((int) Double.parseDouble(d[6])) + "");
                    behave.setNot_facing_front(((int) Double.parseDouble(d[7])) + "");
                    behave.setYawning(((int) Double.parseDouble(d[8])) + "");
                    behave.setHead_lowered(((int) Double.parseDouble(d[9])) + "");

                    if (dangerousbehave * 10 < 100) {
                        score -= dangerousbehave * 10;
                    } else {
                        score = 0;
                    }
                    d = wearAvgList.get(0).split("\t");
                    history1.setConcentration(score + "%");
                    history1.setHeart_avg(((int) Double.parseDouble(d[3])) + "");
                    history1.setSysPres_avg(((int) Double.parseDouble(d[4])) + "");
                    history1.setDiaPres_avg(((int) Double.parseDouble(d[2])) + "");
                    history1.setOxy_avg(((int) Double.parseDouble(d[1])) + "");
                    d = envAvgList.get(0).split("\t");
                    history1.setDrivingCO2(((int) Double.parseDouble(d[3])) + "");
                    history1.setDrivingTemp(((int) Double.parseDouble(d[1])) + "");
                    history1.setDrivingTVOC(((int) Double.parseDouble(d[2])) + "");
                    history1.setDrivingWet(((int) Double.parseDouble(d[4])) + "");

                    //插入历史记录数据库
                    insertHistory(history1, historyid);


                    //插入危险驾驶行为数据库
                    insertBehave(behave, historyid);
                }
                try {
                    session.close();
                } catch (IoTDBConnectionException e) {
                    e.printStackTrace();
                }
            }
        });
      thread.start();
    }

    private void insertUserHistory(int historyid, String userId) {
        MysqlOperation sql = new MysqlOperation();
        sql.userHistoryDao=new MysqlOperation.UserHistoryDao();
        try {
            sql.userHistoryDao.insert(historyid,userId);
            System.out.println("Mysql连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void insertBehave(Behave behave,int historyid) {
        MysqlOperation sql = new MysqlOperation();
        sql.behaveDao=new MysqlOperation.BehaveDao();
        try {
            sql.behaveDao.insert(behave,historyid);
            System.out.println("Mysql连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void insertHistory(History history1,int historyid) {
        MysqlOperation sql = new MysqlOperation();
        sql.historyDao=new MysqlOperation.HistoryDao();
        try {
            sql.historyDao.insert(history1,historyid);
            System.out.println("Mysql连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void insertWear(Double d, Double d1, Double d2, Double d3, int i,int historyid) {


            MysqlOperation sql = new MysqlOperation();
            sql.wearDao=new MysqlOperation.WearDao();
            try {
                sql.wearDao.insert(d,d1,d2,d3,i,historyid);
                System.out.println("Mysql连接成功");
//                Message message=new Message();
//                message.obj=demos;
//                handler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }

    }


//    private String[] executeQuery(long start, long end, String sql){
//        String[] WearList = new String[0];
//        try {
//            SessionDataSet dataSet = session.executeQueryStatement(sql);
//            Log.d("mqtt", String.valueOf(dataSet.getColumnNames()));
//            System.out.println(dataSet);
//            while (dataSet.hasNext()) {
//                Log.d("mqtt", String.valueOf(dataSet.next()));
//                String[] stringList = String.valueOf(dataSet.next()).split(" ");
//                System.out.println(Arrays.toString(stringList));
//                Log.d("mqtt",Arrays.toString(stringList));
//                dataSet.next();
//            }
//        } catch (StatementExecutionException e) {
//            e.printStackTrace();
//        } catch (IoTDBConnectionException e) {
//            e.printStackTrace();
//        }
//        return WearList;
//    }
//private void insertWear(Double d, Double d1, Double d2, Double d3, int i,int historyid) {
//    new Thread(){
//        @Override
//        public void run() {
//            super.run();
//            MysqlOperation sql = new MysqlOperation();
//            sql.wearDao=new MysqlOperation.WearDao();
//            try {
//                sql.wearDao.insert(d,d1,d2,d3,i,historyid);
//                System.out.println("Mysql连接成功");
////                Message message=new Message();
////                message.obj=demos;
////                handler.sendMessage(message);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }.start();
//}

}
